package net.ecpt.crm.services;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.ofbiz.autoconfig.auto.EntitySQLProcessor;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.WvDatetimeUtils;

import javolution.util.FastList;
import javolution.util.FastMap;

public class CrmServices {
    public static final String module = CrmServices.class.getName();

    public static String listToString2(List list, String separator) {
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < list.size(); i++) {
	    sb.append("'").append(list.get(i)).append("'").append(separator);
	}
	return list.isEmpty() ? "" : sb.toString().substring(0, sb.toString().length() - 1);
    }

    /**
     * 未联系的客户
     */
    private static Long getCrmCustomerActivity(Delegator delegator, List ownerUserIdList, Long fromDateNum,
	    Long thruDateNum) throws GenericEntityException {
//		超过7天未联系的客户
//		1 个
//		超过15天未联系的客户
//		1 个
//		超过30天未联系的客户
//		1 个
//		超过3个月未联系的客户
//		0 个
//		超过6个月未联系的客户
//		0 个
//		逾期未联系的客户
//		1 个
	Map<String, Object> result = new HashMap();
	List mainCond0 = new ArrayList();
	mainCond0.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
	Timestamp today = new Timestamp(new Date().getTime());
//    	Timestamp fromDate1 =WvDatetimeUtils.getLastDay(today, new Long(-15));
//    	Timestamp thruDate1 =WvDatetimeUtils.getLastDay(today, new Long(-7));
	Timestamp fromDate1 = WvDatetimeUtils.getLastDay(today, new Long(fromDateNum));
	Timestamp thruDate1 = WvDatetimeUtils.getLastDay(today, new Long(thruDateNum));

	List mainCond1 = mainCond0;
	mainCond1.add(EntityCondition.makeCondition("updateTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate1));
	mainCond1.add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, thruDate1));
	mainCond1.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	Long crmCustomerNum = delegator.findCountByCondition("CrmCustomer",
		EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, null);

	return crmCustomerNum;
    }

//	private static List getBusinessReportAddPersonList_old(Delegator delegator,String inventoryId)throws Exception{
//		   List personDataList = new ArrayList();
//		   Map personDataCollection = new HashMap();
//			try {
//				   ArrayList<EntityCondition> mainCond = new ArrayList<>();
//				   mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "7"));
//				   List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness", EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);
//				   for (GenericValue crmBusiness : crmBusinessList) {
//					   
//					   String businessId =crmBusiness.getString("id");
//					   String ownerUserId =crmBusiness.getString("ownerUserId");
//					   String statusId =crmBusiness.getString("statusId");
//					   
//					   
//					   
//					   
//					   List<GenericValue> crmBusinessItemList =  delegator.findByAnd("CrmBusinessItem", UtilMisc.toMap("businessId", businessId,"inventoryId",inventoryId,"typeId","1"), null, true);
//					   
//					   for (GenericValue crmBusinessItem : crmBusinessItemList) {
//						   Debug.log("crmBusinessItem ="+crmBusinessItem);
//						   
//					   		// 冷冻
//						   BigDecimal estimatedFreeze = crmBusinessItem.getBigDecimal("estimatedFreeze");
//						   // 冷藏
//						   BigDecimal estimatedRefrigerate = crmBusinessItem.getBigDecimal("estimatedRefrigerate");
//						   // 恒温
//						   BigDecimal estimatedConstant = crmBusinessItem.getBigDecimal("estimatedConstant");
//						   // 常温
//						   BigDecimal estimatedNormal = crmBusinessItem.getBigDecimal("estimatedNormal");
//						   
//						   Map personData = new HashMap();
//						   personData.put("ownerUserId", ownerUserId);
//						   personData.put("statusId", statusId);
////						   personData.put("estimatedSalesAmount", estimatedSalesAmount);
//						   personData.put("estimatedFreeze", estimatedFreeze);
//						   personData.put("estimatedRefrigerate", estimatedRefrigerate);
//						   personData.put("estimatedConstant", estimatedConstant);
//						   personData.put("estimatedNormal", estimatedNormal);
//						   personData.put("businessItemNum", 1);
//						   Debug.log("personDataCollection = "+personDataCollection);
//						   Debug.log("personData = "+personData);
//						  
//						   personDataCollection =addPersonDataCollectionEstimatedNum(delegator, personDataCollection, personData);
//						   Debug.log("personDataCollection = "+personDataCollection);
//							   
//						  
//					   
//					   }
//					   
//			    		
//					   
//				   }
//				   
//				
//				personDataList =   new ArrayList<Map>(personDataCollection.values());
//				
//				
//				
//				//按照商机数量进行排序
//				Collections.sort(personDataList,new Comparator<Map>() {
//					@Override
//					public int compare(Map obj1, Map obj2) {
//						//int i = ((Integer)obj1.get("businessNum")).compareTo((Integer)obj2.get("businessNum"));//正序
//						int i = ((Integer)obj2.get("businessItemNum")).compareTo((Integer)obj1.get("businessItemNum"));
//						return i;//这里返回的只是一个int类型的数据
//					}
//				});
//				
//				
//		  
//		   	
//			} catch (Exception e) {
//				Debug.logError(e.getMessage(), module);
//			}
//		    
//		  
//		    Debug.log("personDataList ="+personDataList);
//		   return personDataList;
//		   
//	    }
//	

    /**
     * 预入仓报告
     */
    public static Map<String, Object> forecastWmsInventoryAnalysis(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("forecastWmsInventoryAnalysis == start");
	String ownerUserId = userLogin.getString("userLoginId");
	// String buId = (String) context.get("buId");
	// 所属bu
	String onlyBu = (String) context.get("onlyBu");
	List<String> baseIdList = new ArrayList();
	try {
	    if ("Y".equals(onlyBu)) {

		List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId",
				"COMPANY_EMPLOYEE"),
			null, false);
		if (UtilValidate.isNotEmpty(coRelationshipList)) {
		    for (int i = 0; i < coRelationshipList.size(); i++) {
			GenericValue coRelationship = coRelationshipList.get(i);
			String partyIdFrom = coRelationship.getString("partyIdFrom");
			baseIdList.add(partyIdFrom);
		    }
		}

	    }
	    Debug.log("baseIdList " + baseIdList);
	    EntityCondition mainCond = null;
	    List<EntityCondition> andExprs = FastList.newInstance();
	    if (UtilValidate.isNotEmpty(baseIdList)) {
		andExprs.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, baseIdList));
	    }
	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if (andExprs.size() > 0) {
		mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
	    }
	    Debug.log("mainCond " + mainCond);
	    // 按仓库统计 销售情况
	    List dataListByWarehouse = new ArrayList();

	    List orderBy = UtilMisc.toList("ownerBuId");
	    List<GenericValue> entityList = delegator.findList("CrmWmsInventory", mainCond, null, orderBy, null, true);

	    Debug.log("entityList " + entityList);

	    for (GenericValue entity : entityList) {
		Map<String, Object> map = FastMap.newInstance();

		Debug.log("entity = " + entity);
		String id = entity.getString("id");

		String warehouseName = entity.getString("warehouseName");
		// 建设冷冻容量
		BigDecimal buildingFreeze = entity.getBigDecimal("buildingFreeze");
		buildingFreeze = UtilValidate.isEmpty(buildingFreeze) ? BigDecimal.ZERO : buildingFreeze;
		// 已使用冷冻
		BigDecimal physicalFreeze = entity.getBigDecimal("physicalFreeze");
		physicalFreeze = UtilValidate.isEmpty(physicalFreeze) ? BigDecimal.ZERO : physicalFreeze;
		// 剩余量
		BigDecimal availableFreeze = buildingFreeze.subtract(physicalFreeze);

		// 建设冷藏容量
		BigDecimal buildingRefrigerate = entity.getBigDecimal("buildingRefrigerate");
		buildingRefrigerate = UtilValidate.isEmpty(buildingRefrigerate) ? BigDecimal.ZERO : buildingRefrigerate;
		// 已使用冷藏
		BigDecimal physicalRefrigerate = entity.getBigDecimal("physicalRefrigerate");
		physicalRefrigerate = UtilValidate.isEmpty(physicalRefrigerate) ? BigDecimal.ZERO : physicalRefrigerate;
		BigDecimal availableRefrigerate = buildingRefrigerate.subtract(physicalRefrigerate);

		// 建设恒温容量
		BigDecimal buildingConstant = entity.getBigDecimal("buildingConstant");
		buildingConstant = UtilValidate.isEmpty(buildingConstant) ? BigDecimal.ZERO : buildingConstant;
		// 已使用恒温
		BigDecimal physicalConstant = entity.getBigDecimal("physicalConstant");
		physicalConstant = UtilValidate.isEmpty(physicalConstant) ? BigDecimal.ZERO : physicalConstant;
		BigDecimal availableConstant = buildingConstant.subtract(physicalConstant);

		// 建设常温容量
		BigDecimal buildingNormal = entity.getBigDecimal("buildingNormal");
		buildingNormal = UtilValidate.isEmpty(buildingNormal) ? BigDecimal.ZERO : buildingNormal;
		// 已使用常温
		BigDecimal physicalNormal = entity.getBigDecimal("physicalNormal");
		physicalNormal = UtilValidate.isEmpty(physicalNormal) ? BigDecimal.ZERO : physicalNormal;
		BigDecimal availableNormal = buildingNormal.subtract(physicalNormal);

		map.put("warehouseName", warehouseName);

		map.put("availableFreeze", availableFreeze);
		map.put("availableRefrigerate", availableRefrigerate);
		map.put("availableConstant", availableConstant);
		map.put("availableNormal", availableNormal);

		Debug.log("map = " + map);

		Map estimatedInventory = forecastInventory(delegator, id);
		Debug.log("estimatedInventory = " + estimatedInventory);
		BigDecimal estimatedFreeze = (BigDecimal) estimatedInventory.get("estimatedFreeze");
		BigDecimal estimatedRefrigerate = (BigDecimal) estimatedInventory.get("estimatedRefrigerate");
		BigDecimal estimatedConstant = (BigDecimal) estimatedInventory.get("estimatedConstant");
		BigDecimal estimatedNormal = (BigDecimal) estimatedInventory.get("estimatedNormal");
		BigDecimal estimatedFreezeNextMonth = (BigDecimal) estimatedInventory.get("estimatedFreezeNextMonth");
		BigDecimal estimatedRefrigerateNextMonth = (BigDecimal) estimatedInventory
			.get("estimatedRefrigerateNextMonth");
		BigDecimal estimatedConstantNextMonth = (BigDecimal) estimatedInventory
			.get("estimatedConstantNextMonth");
		BigDecimal estimatedNormalNextMonth = (BigDecimal) estimatedInventory.get("estimatedNormalNextMonth");

		BigDecimal estimatedFreezeNext2Month = (BigDecimal) estimatedInventory.get("estimatedFreezeNext2Month");
		BigDecimal estimatedRefrigerateNext2Month = (BigDecimal) estimatedInventory
			.get("estimatedRefrigerateNext2Month");
		BigDecimal estimatedConstantNext2Month = (BigDecimal) estimatedInventory
			.get("estimatedConstantNext2Month");
		BigDecimal estimatedNormalNext2Month = (BigDecimal) estimatedInventory.get("estimatedNormalNext2Month");

		BigDecimal estimatedFreezeNext3Month = (BigDecimal) estimatedInventory.get("estimatedFreezeNext3Month");
		BigDecimal estimatedRefrigerateNext3Month = (BigDecimal) estimatedInventory
			.get("estimatedRefrigerateNext3Month");
		BigDecimal estimatedConstantNext3Month = (BigDecimal) estimatedInventory
			.get("estimatedConstantNext3Month");
		BigDecimal estimatedNormalNext3Month = (BigDecimal) estimatedInventory.get("estimatedNormalNext3Month");

		map.put("estimatedFreeze", estimatedFreeze);
		map.put("estimatedFreezeNextMonth", estimatedFreezeNextMonth);
		map.put("estimatedFreezeNext2Month", estimatedFreezeNext2Month);
		map.put("estimatedFreezeNext3Month", estimatedFreezeNext3Month);

		map.put("estimatedRefrigerate", estimatedRefrigerate);
		map.put("estimatedRefrigerateNextMonth", estimatedRefrigerateNextMonth);
		map.put("estimatedRefrigerateNext2Month", estimatedRefrigerateNext2Month);
		map.put("estimatedRefrigerateNext3Month", estimatedRefrigerateNext3Month);

		map.put("estimatedConstant", estimatedConstant);
		map.put("estimatedConstantNextMonth", estimatedConstantNextMonth);
		map.put("estimatedConstantNext2Month", estimatedConstantNext2Month);
		map.put("estimatedConstantNext3Month", estimatedConstantNext3Month);

		map.put("estimatedNormal", estimatedNormal);
		map.put("estimatedNormalNextMonth", estimatedNormalNextMonth);
		map.put("estimatedNormalNext2Month", estimatedNormalNext2Month);
		map.put("estimatedNormalNext3Month", estimatedNormalNext3Month);
		Debug.log("map = " + map);
		dataListByWarehouse.add(map);
		Debug.log("dataListByWarehouse = " + dataListByWarehouse);
	    }

	    Map<String, Object> workMap = FastMap.newInstance();

	    workMap.put("dataListByWarehouse", dataListByWarehouse);

	    result.put("workMap", workMap);
	    Debug.log("forecastWmsInventoryAnalysis == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

//	public static void getCategoryCustomer(Delegator delegator, Map customerListByProductCategory) {
//		String sql = "select count(c.ID) 数量,min(d.DESCRIPTION) 品类 " +
//				"		from CRM_CUSTOMER c  left join DATA_DICTIONARY d on d.DICTIONARY_ID =  c.PRODUCT_CATEGORY "
//				+ "group by c.PRODUCT_CATEGORY";
//		Map sqlCommand = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql));
//		customerListByProductCategory.put("records", sqlCommand.get("records"));// 记录
//		customerListByProductCategory.put("columns", sqlCommand.get("columns"));// 列名
//	}
    private static Map getCategoryCustomer(Delegator delegator) {
	Map<String, Object> map = new HashMap<String, Object>();
	String sql = "select count(c.ID) 数量,min(IFNULL(d.DESCRIPTION, '其他')) 品类  "
		+ "		from CRM_CUSTOMER c  left join DATA_DICTIONARY d on d.DICTIONARY_ID =  c.PRODUCT_CATEGORY "
		+ "group by c.PRODUCT_CATEGORY";
	Map sqlCommand = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql));
	map.put("records", sqlCommand.get("records"));// 记录
	map.put("columns", sqlCommand.get("columns"));// 列名

	return map;
    }

    private static List<String> getMonthes() {
	List<String> chartDataKeyList = new ArrayList<>();
	Calendar cal = Calendar.getInstance();
	cal.setTime(new Date());
	SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
	for (int i = 0; i < 12; i++) {
	    Date time = cal.getTime();
	    String formatDate = dft.format(time);
	    chartDataKeyList.add(formatDate);
	    cal.add(Calendar.MONTH, -1);
	}
	Collections.reverse(chartDataKeyList);
	return chartDataKeyList;
    }

    private static List listUserLoginIdByPersonTypeId(Delegator delegator, String personTypeId, String ownerUserId)
	    throws GenericEntityException {
	List ownerUserIdList = new ArrayList();
	// 本人及下属
	if ("2".equals(personTypeId)) {
	    List<GenericValue> subordinateList = delegator.findByAnd("UserLogin",
		    UtilMisc.toMap("superiorId", ownerUserId), null, false);
	    for (GenericValue subordinate : subordinateList) {
		String subordinateUserLoginId = subordinate.getString("userLoginId");
		ownerUserIdList.add(subordinateUserLoginId);
	    }
	    ownerUserIdList.add(ownerUserId);
	} else if ("1".equals(personTypeId)) {
	    ownerUserIdList.add(ownerUserId);
	} else {
	    ownerUserId = personTypeId;
	    ownerUserIdList.add(ownerUserId);
	}

	return ownerUserIdList;
    }

    private static List listUserLoginIdByBuId(Delegator delegator, String ownerBuId) throws GenericEntityException {
	List ownerUserIdList = new ArrayList();

	List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship", UtilMisc.toMap("partyIdFrom",
		ownerBuId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE"), null, false);
	if (UtilValidate.isNotEmpty(coRelationshipList)) {
	    for (int i = 0; i < coRelationshipList.size(); i++) {
		GenericValue coRelationship = coRelationshipList.get(i);
		String partyIdTo = coRelationship.getString("partyIdTo");
		ownerUserIdList.add(partyIdTo);
	    }
	}

	return ownerUserIdList;
    }

    public static Map<String, Object> crmCustomerNumReport(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	try {
	    List ownerUserIdList = new ArrayList();

	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }

	    chartDataKeyList = getMonthes();
	    Debug.log("monthes ===" + chartDataKeyList);
	    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    for (String string : chartDataKeyList) {
		Map<String, Object> map = new HashMap<>();
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		ArrayList<EntityCondition> mainCond0 = new ArrayList<>();
		if (UtilValidate.isNotEmpty(ownerUserIdList)) {
		    mainCond0.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
		}
		Debug.log("ownerUserIdList", ownerUserIdList);
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
		mainCond0.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
		Long crmCustomerNum = delegator.findCountByCondition("CrmCustomer",
			EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);

		Debug.log("crmCustomerNum", crmCustomerNum);
		if (UtilValidate.isEmpty(crmCustomerNum)) {
		    crmCustomerNum = 0L;
		}
		map.put("name", string);
		map.put("value", crmCustomerNum);
		chartData.add(map);
		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string);
		chartDataListItem.add(crmCustomerNum);
		chartDataList.add(chartDataListItem);
	    }
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("chartData", chartData);
	workMap.put("chartDataList", chartDataList);
	workMap.put("chartDataKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	result.put("records", chartDataList);
	result.put("columns", chartDataKeyList);
	Debug.log("workMap ===" + workMap);
	return result;
    }

    public static Map<String, Object> orderByCrmWmsInventory(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	List nfsList = new ArrayList();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String userLoginId = userLogin.getString("userLoginId");

	try {
	    String buId = getBuIdByUserLoginId(delegator, userLoginId);

	    List<GenericValue> entityList = delegator.findByAnd("CrmWmsInventory", UtilMisc.toMap("statusId", "Y","removed","N"),
		    null, true);
	    for (GenericValue entity : entityList) {
		Debug.log("entity ===" + entity);
		Map nfsMap = new HashMap();
		String warehouseName = entity.getString("warehouseName");
		String id = entity.getString("id");
		String ownerBuId = entity.getString("ownerBuId");

		nfsMap.put("title", warehouseName);
		nfsMap.put("text", warehouseName);
		nfsMap.put("key", id);
		nfsMap.put("value", id);
		nfsMap.put("orderByNum", 1);

		if (UtilValidate.isNotEmpty(buId) && buId.equals(ownerBuId)) {
		    nfsMap.put("orderByNum", 5);
		}
		nfsList.add(nfsMap);

	    }

	    Collections.sort(nfsList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((Integer) obj2.get("orderByNum")).compareTo((Integer) obj1.get("orderByNum"));// 倒序
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	result.put("nfsList", nfsList);
	Debug.log("nfsList ===" + nfsList);
	return result;
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String, Object> orderByCrmWmsInventory2(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	List nfsList = new ArrayList();

	try {
	    List<GenericValue> entityList = delegator.findByAnd("CrmWmsInventory", UtilMisc.toMap("statusId", "Y","removed","N"),
		    null, true);
	    for (GenericValue entity : entityList) {
		Debug.log("entity ===" + entity);
		Map nfsMap = new HashMap();
		String warehouseName = entity.getString("warehouseName");
		Long warehouseCodeNum = entity.getLong("warehouseCodeNum");
		String id = entity.getString("id");

		nfsMap.put("title", warehouseName);
		nfsMap.put("text", warehouseName);
		nfsMap.put("key", id);
		nfsMap.put("value", id);
		nfsMap.put("orderByNum", warehouseCodeNum);
		nfsList.add(nfsMap);

	    }
	    Collections.sort(nfsList, new Comparator<Map>() {
		@Override
		public int compare(Map obj1, Map obj2) {
		    int i = ((Long) obj1.get("orderByNum")).compareTo((Long) obj2.get("orderByNum"));// 倒序
		    return i;// 这里返回的只是一个int类型的数据
		}
	    });

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	result.put("nfsList", nfsList);
	Debug.log("nfsList ===" + nfsList);
	return result;
    }
    
    private static String getPersonName(Delegator delegator, String userLoginId) throws GenericEntityException {
	String result = "";

	GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), true);

	if (UtilValidate.isNotEmpty(userLogin)) {
	    GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", userLogin.getString("partyId")),
		    false);
	    if (UtilValidate.isNotEmpty(person)) {
		String personName = person.getString("name");
		result = personName;
	    }
	}
	return result;
    }

    private static String getBuIdByUserLoginId(Delegator delegator, String userLoginId) throws GenericEntityException {
	String result = "";

	List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship", UtilMisc.toMap("partyIdTo",
		userLoginId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId", "COMPANY_EMPLOYEE"), null, true);
	GenericValue coRelationship = EntityUtil.getFirst(coRelationshipList);
	if (UtilValidate.isNotEmpty(coRelationship)) {
	    result = coRelationship.getString("partyIdFrom");
	}

	return result;
    }

    public static Map<String, Object> crmCustomerNumReportTable(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	try {

	    List ownerUserIdList = new ArrayList();

	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    chartDataKeyList = getMonthes();
	    Debug.log("monthes ===" + chartDataKeyList);
	    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Map<String, Object> map = new HashMap<>();
	    for (String string : chartDataKeyList) {
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		ArrayList<EntityCondition> mainCond0 = new ArrayList<>();
		if (UtilValidate.isNotEmpty(ownerUserIdList)) {
		    mainCond0.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
		}
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
		mainCond0.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
		Long crmCustomerNum = delegator.findCountByCondition("CrmCustomer",
			EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);
		if (UtilValidate.isEmpty(crmCustomerNum)) {
		    crmCustomerNum = 0L;
		}
		map.put(string, formatNum(crmCustomerNum));

		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string);
		chartDataListItem.add(formatNum(crmCustomerNum));
		chartDataList.add(chartDataListItem);
	    }
	    chartData.add(map);
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("itemList", chartData);
	workMap.put("itemListTable", chartDataList);
	workMap.put("itemListKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	Debug.log("workMap ===" + workMap);
	return result;
    }

    public static Map<String, Object> crmContractNumReport(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	String ownerBuId = (String) context.get("ownerBuId");
	chartDataKeyList = getMonthes();
	Debug.log("monthes ===" + chartDataKeyList);
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
	    List ownerUserIdList = new ArrayList();

	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    for (String string : chartDataKeyList) {
		Map<String, Object> map = new HashMap<>();
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		ArrayList<EntityCondition> mainCond0 = new ArrayList<>();
		if (UtilValidate.isNotEmpty(ownerUserIdList)) {
		    mainCond0.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
		}
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
		Long crmCustomerNum = delegator.findCountByCondition("CrmContract",
			EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);
		if (UtilValidate.isEmpty(crmCustomerNum)) {
		    crmCustomerNum = 0L;
		}
		map.put("name", string.replace("-", ""));
		map.put("value", crmCustomerNum);
		chartData.add(map);
		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string.replace("-", ""));
		chartDataListItem.add(crmCustomerNum);
		chartDataList.add(chartDataListItem);
	    }
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("chartData", chartData);
	workMap.put("chartDataList", chartDataList);
	workMap.put("chartDataKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	result.put("records", chartDataList);
	result.put("columns", chartDataKeyList);
	return result;
    }

    private static String formatNum(Long obj) {
	DecimalFormat df = new DecimalFormat("##,##0");
	String format = df.format(obj);
	return format;
    }

    private static String formatMoney(Long obj) {
	DecimalFormat df = new DecimalFormat("##,##0.00");
	String format = df.format(obj);
	return format;
    }

    public static Map<String, Object> crmContractNumReportTable(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	chartDataKeyList = getMonthes();
	Debug.log("monthes ===" + chartDataKeyList);
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Map<String, Object> map = new HashMap<>();
	try {
//			List ownerUserIdList = getUserLoginAll(personTypeId,ownerBuId, delegator,  ownerUserId);
	    List ownerUserIdList = new ArrayList();

	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    for (String string : chartDataKeyList) {
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		ArrayList<EntityCondition> mainCond0 = new ArrayList<>();
		if (UtilValidate.isNotEmpty(ownerUserIdList)) {
		    mainCond0.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.IN, ownerUserIdList));
		}
		mainCond0.add(
			EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));
		Long crmCustomerNum = delegator.findCountByCondition("CrmContract",
			EntityCondition.makeCondition(mainCond0, EntityOperator.AND), null, null);
		if (UtilValidate.isEmpty(crmCustomerNum)) {
		    crmCustomerNum = 0L;
		}
		map.put(string, formatNum(crmCustomerNum));
		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string);
		chartDataListItem.add(formatNum(crmCustomerNum));
		chartDataList.add(chartDataListItem);
	    }
	    chartData.add(map);
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("itemList", chartData);
	workMap.put("itemListTable", chartDataList);
	workMap.put("itemListKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	return result;
    }

    public static Map<String, Object> crmContractMoneyReport(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	String ownerBuId = (String) context.get("ownerBuId");
	chartDataKeyList = getMonthes();
	Debug.log("monthes ===" + chartDataKeyList);
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
//			List ownerUserIdList = getUserLoginAll(personTypeId,ownerBuId, delegator,  ownerUserId);
	    List ownerUserIdList = new ArrayList();

	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    String joinOwnerUserId = listToString2(ownerUserIdList, ",");
	    for (String string : chartDataKeyList) {
		Map<String, Object> map = new HashMap<>();
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		String startDate = df.format(fromDate);
		String endDate = df.format(thruDate);
		Long newCrmContractTotalAmount = 0L;
		String sql1 = "select sum(c.money) moneySum " + "from CRM_CONTRACT c  " + "where c.CREATE_TIME > '"
			+ startDate + "' and c.CREATE_TIME <'" + endDate + "' ";
		if (UtilValidate.isNotEmpty(ownerUserIdList)) {
		    sql1 = sql1 + "and c.OWNER_USER_ID in (" + joinOwnerUserId + ")";
		}
		Debug.log("sql1=" + sql1);
		Map sqlCommand1 = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql1));
		Debug.log(",sqlCommand1:" + sqlCommand1);
		List<List<Object>> records1 = (List<List<Object>>) sqlCommand1.get("records");
		if (UtilValidate.isNotEmpty(records1)) {
		    List<Object> list = records1.get(0);
		    Debug.log(",list:" + list);
		    if (UtilValidate.isNotEmpty(list)) {
			Object o1 = list.get(0);
			if (UtilValidate.isNotEmpty(o1)) {
			    BigDecimal o = (BigDecimal) o1;
			    newCrmContractTotalAmount = o.longValue();
			}

		    }
		}

		map.put("name", string.replace("-", ""));
		map.put("value", newCrmContractTotalAmount);
		chartData.add(map);
		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string.replace("-", ""));
		chartDataListItem.add(newCrmContractTotalAmount);
		chartDataList.add(chartDataListItem);
	    }
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("chartData", chartData);
	workMap.put("chartDataList", chartDataList);
	workMap.put("chartDataKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	result.put("records", chartDataList);
	result.put("columns", chartDataKeyList);
	return result;
    }

    public static Map<String, Object> crmContractMoneyReportTable(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	String ownerBuId = (String) context.get("ownerBuId");
	chartDataKeyList = getMonthes();
	Debug.log("monthes ===" + chartDataKeyList);
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Map<String, Object> map = new HashMap<>();
	try {
//			List ownerUserIdList = getUserLoginAll(personTypeId,ownerBuId, delegator,  ownerUserId);
	    List ownerUserIdList = new ArrayList();

	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    String joinOwnerUserId = listToString2(ownerUserIdList, ",");
	    for (String string : chartDataKeyList) {
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		String startDate = df.format(fromDate);
		String endDate = df.format(thruDate);
		Long newCrmContractTotalAmount = 0L;
		String sql1 = "select sum(c.money) moneySum " + "from CRM_CONTRACT c  " + "where c.CREATE_TIME > '"
			+ startDate + "' and c.CREATE_TIME <'" + endDate + "' ";
		if (UtilValidate.isNotEmpty(ownerUserIdList)) {
		    sql1 = sql1 + "and c.OWNER_USER_ID in (" + joinOwnerUserId + ")";
		}
		Debug.log("sql1=" + sql1);
		Map sqlCommand1 = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql1));
		Debug.log(",sqlCommand1:" + sqlCommand1);
		List<List<Object>> records1 = (List<List<Object>>) sqlCommand1.get("records");
		if (UtilValidate.isNotEmpty(records1)) {
		    List<Object> list = records1.get(0);
		    Debug.log(",list:" + list);
		    if (UtilValidate.isNotEmpty(list)) {
			Object o1 = list.get(0);
			if (UtilValidate.isNotEmpty(o1)) {
			    BigDecimal o = (BigDecimal) o1;
			    newCrmContractTotalAmount = o.longValue();
			}

		    }
		}

		map.put(string, formatNum(newCrmContractTotalAmount));
		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string);
		chartDataListItem.add(formatNum(newCrmContractTotalAmount));
		chartDataList.add(chartDataListItem);
	    }
	    chartData.add(map);
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("itemList", chartData);
	workMap.put("itemListTable", chartDataList);
	workMap.put("itemListKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	result.put("records", chartDataList);
	result.put("columns", chartDataKeyList);
	return result;
    }

    public static Map<String, Object> crmReceivablesMoneyReport(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	chartDataKeyList = getMonthes();
	Debug.log("monthes ===" + chartDataKeyList);
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
	    List ownerUserIdList = new ArrayList();
	    // 本人及下属
	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    String joinOwnerUserId = listToString2(ownerUserIdList, ",");
	    for (String string : chartDataKeyList) {
		Map<String, Object> map = new HashMap<>();
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		String startDate = df.format(fromDate);
		String endDate = df.format(thruDate);
		Long newCrmContractTotalAmount = 0L;
		String sql3 = "select sum(c.money) moneySum " + "from CRM_RECEIVABLES c  " + "where c.CREATE_TIME > '"
			+ startDate + "' and c.CREATE_TIME <'" + endDate + "' and c.OWNER_USER_ID in ("
			+ joinOwnerUserId + ")";
		Debug.log("sql3=" + sql3);
		Map sqlCommand1 = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql3));
		Debug.log(",sqlCommand1:" + sqlCommand1);
		List<List<Object>> records1 = (List<List<Object>>) sqlCommand1.get("records");
		if (UtilValidate.isNotEmpty(records1)) {
		    List<Object> list = records1.get(0);
		    Debug.log(",list:" + list);
		    if (UtilValidate.isNotEmpty(list)) {
			Object o1 = list.get(0);
			if (UtilValidate.isNotEmpty(o1)) {
			    BigDecimal o = (BigDecimal) o1;
			    newCrmContractTotalAmount = o.longValue();
			}

		    }
		}

		map.put("name", string.replace("-", ""));
		map.put("value", newCrmContractTotalAmount);
		chartData.add(map);
		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string.replace("-", ""));
		chartDataListItem.add(newCrmContractTotalAmount);
		chartDataList.add(chartDataListItem);
	    }
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("chartData", chartData);
	workMap.put("chartDataList", chartDataList);
	workMap.put("chartDataKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	result.put("records", chartDataList);
	result.put("columns", chartDataKeyList);
	return result;
    }

    public static Map<String, Object> crmReceivablesMoneyReportTable(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	chartDataKeyList = getMonthes();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	Debug.log("monthes ===" + chartDataKeyList);
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Map<String, Object> map = new HashMap<>();
	try {
	    List ownerUserIdList = new ArrayList();
	    // 本人及下属
	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    String joinOwnerUserId = listToString2(ownerUserIdList, ",");
	    for (String string : chartDataKeyList) {
		Date date = df.parse(string + "-01 00:00:00");
		String lastMonth = df.format(date);
		Timestamp fromDate = Timestamp.valueOf(lastMonth);
		Timestamp thruDate = WvDatetimeUtils.getEndDate(fromDate);
		Debug.log("fromTime", fromDate);
		Debug.log("thruDate", thruDate);
		String startDate = df.format(fromDate);
		String endDate = df.format(thruDate);
		Long newCrmContractTotalAmount = 0L;
		String sql3 = "select sum(c.money) moneySum " + "from CRM_RECEIVABLES c  " + "where c.CREATE_TIME > '"
			+ startDate + "' and c.CREATE_TIME <'" + endDate + "' and c.OWNER_USER_ID in ("
			+ joinOwnerUserId + ")";
		Debug.log("sql3=" + sql3);
		Map sqlCommand1 = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql3));
		Debug.log(",sqlCommand1:" + sqlCommand1);
		List<List<Object>> records1 = (List<List<Object>>) sqlCommand1.get("records");
		if (UtilValidate.isNotEmpty(records1)) {
		    List<Object> list = records1.get(0);
		    Debug.log(",list:" + list);
		    if (UtilValidate.isNotEmpty(list)) {
			Object o1 = list.get(0);
			if (UtilValidate.isNotEmpty(o1)) {
			    BigDecimal o = (BigDecimal) o1;
			    newCrmContractTotalAmount = o.longValue();
			}

		    }
		}

		map.put(string, formatMoney(newCrmContractTotalAmount));

		List<Object> chartDataListItem = new ArrayList<Object>();
		chartDataListItem.add(string);
		chartDataListItem.add(formatMoney(newCrmContractTotalAmount));
		chartDataList.add(chartDataListItem);
	    }
	    chartData.add(map);
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	workMap.put("itemList", chartData);
	workMap.put("itemListTable", chartDataList);
	workMap.put("itemListKeyList", chartDataKeyList);
	result.put("workMap", workMap);
	result.put("records", chartDataList);
	result.put("columns", chartDataKeyList);
	return result;
    }

    public static Map<String, Object> crmIndustryReport(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	List itemList = new ArrayList();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	try {
	    List ownerUserIdList = new ArrayList();
	    // 本人及下属
	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    String joinOwnerUserId = listToString2(ownerUserIdList, ",");
	    String sql3 = "select  count(a.ID) 个数,min(d.DESCRIPTION) 行业 "
		    + "from CRM_CUSTOMER a left join DATA_DICTIONARY d on a.INDUSTRY = d.DICTIONARY_ID   where a.OWNER_USER_ID in ("
		    + joinOwnerUserId + ")" + " group by a.INDUSTRY ";
	    Debug.log("sql3=" + sql3);
	    Map sqlCommand1 = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql3));
	    Debug.log(",sqlCommand1:" + sqlCommand1);
	    chartDataList = (List) sqlCommand1.get("records");// 记录
	    chartDataKeyList = (List) sqlCommand1.get("columns");// 列名

	    List records1 = (List) sqlCommand1.get("records");
	    for (int i = 0; i < records1.size(); i++) {
		Map map = new HashMap();
		List subList = (List) records1.get(i);
		Object object = subList.get(0);
		if (UtilValidate.isEmpty(object)) {
		    map.put("key", "未知");
		} else {
		    map.put("key", object);
		}
		map.put("value", subList.get(1));
		chartData.add(map);
	    }
	    for (int i = 0; i < chartDataList.size(); i++) {
		Object object = chartDataList.get(i);
		if (object instanceof List) {
		    Map map = new HashMap();
		    List valueList = (List) chartDataList.get(i);
		    for (int j = 0; j < chartDataKeyList.size(); j++) {
			map.put(chartDataKeyList.get(j), valueList.get(j));
		    }
		    itemList.add(map);
		}
	    }
	    workMap.put("itemList", itemList);//
	    workMap.put("itemListKeyList", chartDataKeyList);// 列名
	    workMap.put("itemListTable", chartDataList);// 记录
	    workMap.put("chartData", chartData);
	    workMap.put("chartDataList", chartDataList);// 记录
	    workMap.put("chartDataKeyList", chartDataKeyList);// 列名
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	result.put("workMap", workMap);
	return result;
    }

    public static Map<String, Object> crmLevelReport(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	List itemList = new ArrayList();
	Map<String, Object> workMap = new HashMap<>();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
	    List ownerUserIdList = new ArrayList();
	    // 本人及下属
	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    String joinOwnerUserId = listToString2(ownerUserIdList, ",");
	    String sql3 = "select  count(a.ID) 个数,min(d.DESCRIPTION) 级别 "
		    + "	 from CRM_CUSTOMER a left join DATA_DICTIONARY d on a.LEVEL = d.DICTIONARY_ID   where a.OWNER_USER_ID in ("
		    + joinOwnerUserId + ")" + " group by a.LEVEL ";
	    Debug.log("sql3=" + sql3);
	    Map sqlCommand1 = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql3));
	    Debug.log(",sqlCommand1:" + sqlCommand1);
	    chartDataList = (List) sqlCommand1.get("records");// 记录
	    chartDataKeyList = (List) sqlCommand1.get("columns");// 列名

	    List records1 = (List) sqlCommand1.get("records");
	    for (int i = 0; i < records1.size(); i++) {
		Map map = new HashMap();
		List subList = (List) records1.get(i);
		Object object = subList.get(0);
		if (UtilValidate.isEmpty(object)) {
		    map.put("key", "未知");
		} else {
		    map.put("key", object);
		}
		map.put("value", subList.get(1));
		chartData.add(map);
	    }
	    for (int i = 0; i < chartDataList.size(); i++) {
		Object object = chartDataList.get(i);
		if (object instanceof List) {
		    Map map = new HashMap();
		    List valueList = (List) chartDataList.get(i);
		    for (int j = 0; j < chartDataKeyList.size(); j++) {
			map.put(chartDataKeyList.get(j), valueList.get(j));
		    }
		    itemList.add(map);
		}
	    }
	    workMap.put("itemList", itemList);//
	    workMap.put("itemListKeyList", chartDataKeyList);// 列名
	    workMap.put("itemListTable", chartDataList);// 记录
	    workMap.put("chartData", chartData);
	    workMap.put("chartDataList", chartDataList);// 记录
	    workMap.put("chartDataKeyList", chartDataKeyList);// 列名
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	result.put("workMap", workMap);
	return result;
    }

    public static Map<String, Object> crmSourceReport(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	List<String> chartDataKeyList = new ArrayList<>();
	Map<String, Object> result = new HashMap<>();
	List<Map<String, Object>> chartData = new ArrayList<>();
	List<List> chartDataList = new ArrayList<>();
	Map<String, Object> workMap = new HashMap<>();
	List itemList = new ArrayList();
	String personTypeId = (String) context.get("personTypeId");
	String ownerBuId = (String) context.get("ownerBuId");
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String ownerUserId = userLogin.getString("userLoginId");
	Debug.log("monthes ===" + chartDataKeyList);
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
	    List ownerUserIdList = new ArrayList();
	    // 本人及下属
	    if (UtilValidate.isNotEmpty(ownerBuId)) {
		ownerUserIdList = listUserLoginIdByBuId(delegator, ownerBuId);
	    } else {
		ownerUserIdList = listUserLoginIdByPersonTypeId(delegator, personTypeId, ownerUserId);
	    }
	    String joinOwnerUserId = listToString2(ownerUserIdList, ",");
	    String sql3 = "select  count(a.ID) 个数,min(d.DESCRIPTION) 来源 "
		    + "	 from CRM_CUSTOMER a left join DATA_DICTIONARY d on a.SOURCE = d.DICTIONARY_ID where a.OWNER_USER_ID in ("
		    + joinOwnerUserId + ")" + " group by a.SOURCE ";
	    Debug.log("sql3=" + sql3);
	    Map sqlCommand1 = EntitySQLProcessor.executeQuery(delegator, UtilMisc.toMap("sqlCommand", sql3));
	    Debug.log(",sqlCommand1:" + sqlCommand1);
	    chartDataList = (List) sqlCommand1.get("records");// 记录
	    chartDataKeyList = (List) sqlCommand1.get("columns");// 列名

	    List records1 = (List) sqlCommand1.get("records");
	    for (int i = 0; i < records1.size(); i++) {
		Map map = new HashMap();
		List subList = (List) records1.get(i);
		Object object = subList.get(0);
		if (UtilValidate.isEmpty(object)) {
		    map.put("key", "未知");
		} else {
		    map.put("key", object);
		}
		map.put("value", subList.get(1));
		chartData.add(map);
	    }
	    for (int i = 0; i < chartDataList.size(); i++) {
		Object object = chartDataList.get(i);
		if (object instanceof List) {
		    Map map = new HashMap();
		    List valueList = (List) chartDataList.get(i);
		    for (int j = 0; j < chartDataKeyList.size(); j++) {
			map.put(chartDataKeyList.get(j), valueList.get(j));
		    }
		    itemList.add(map);
		}
	    }
	    workMap.put("itemList", itemList);//
	    workMap.put("itemListKeyList", chartDataKeyList);// 列名
	    workMap.put("itemListTable", chartDataList);// 记录
	    workMap.put("chartData", chartData);
	    workMap.put("chartDataList", chartDataList);// 记录
	    workMap.put("chartDataKeyList", chartDataKeyList);// 列名
	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}
	result.put("workMap", workMap);
	return result;
    }

    /**
     * 客户省市分布
     */

    // 按省份 统计 全部客户数量，成交客户数量
    public static Map<String, Object> crmCustomerProvinceNumReport(DispatchContext ctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	LocalDispatcher dispatcher = ctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");

	// 省份 全部客户数量，成交客户数量
	List columns = UtilMisc.toList("address", "allCustomer", "dealCustomer");
	List records = new ArrayList();
	try {

//    	    List<GenericValue> gvCrmCustomerList = delegator.findByAnd("CrmCustomer", UtilMisc.toMap("isLock", "0"),null, false);
		
	    List<GenericValue> gvCrmCustomerList = delegator.findByAnd("CrmCustomer", UtilMisc.toMap("removed", "N"),null, false);

	    Map service_context = UtilMisc.toMap("userLogin", userLogin, "geoIdFrom", "CHN", "geoAssocTypeId",
		    "REGIONS");
	    Map service_result = dispatcher.runSync("listGeoAssocInfo", service_context);
	    List<GenericValue> provinceList = (List) service_result.get("nfsList");

	    for (int i = 0; i < provinceList.size(); i++) {
		GenericValue province = provinceList.get(i);
		String geoName = province.getString("geoName");
		String geoId = province.getString("geoId");
		String geoCode = province.getString("geoCode");
		// geoId:CN-11, geoAssocTypeId:REGIONS, geoCode:11,
		int allCustomer = provinceAllCustomerNumber(gvCrmCustomerList, geoId);
		int dealCustomer = provinceDealCustomerNumber(gvCrmCustomerList, geoId);

		List record = new ArrayList();

		record.add(geoName);

		record.add(allCustomer);
		record.add(dealCustomer);

		records.add(record);
	    }
	    result.put("records", records);// 记录
	    result.put("columns", columns);// 列名

	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	} catch (GenericServiceException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    // 该省份全部客户数量

    private static int provinceAllCustomerNumber(List<GenericValue> gvCrmCustomerList, String geoId) {
	int result = 0;
	for (GenericValue gv : gvCrmCustomerList) {
	    Debug.log("geoId = " + geoId);
	    String provinceId = gv.getString("provinceId");
	    Debug.log("provinceId = " + provinceId);
	    if (geoId.equals(provinceId)) {
		Debug.log("result = " + result);
		result = result + 1;
	    }
	}
	return result;
    }
    // 该省份成交客户数量

    private static int provinceDealCustomerNumber(List<GenericValue> gvCrmCustomerList, String geoId) {
	int result = 0;
	for (GenericValue gv : gvCrmCustomerList) {
	    String provinceId = gv.getString("provinceId");
	    // if(UtilValidate.isEmpty(provinceId))continue;
	    String dealStatus = gv.getString("dealStatus");
	    if ("4".equals(dealStatus) && geoId.equals(provinceId)) {
		result = result + 1;
	    }
	}
	return result;
    }

    private static Map getSaleInventory_all(Delegator delegator, String inventoryId) throws Exception {
	Map result = new HashMap();
	BigDecimal estimatedFreezeTotal = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateTotal = BigDecimal.ZERO;
	BigDecimal estimatedConstantTotal = BigDecimal.ZERO;
	BigDecimal estimatedNormalTotal = BigDecimal.ZERO;

	Debug.log("inventoryId =" + inventoryId);
	// 销售人员 的商机
	ArrayList<EntityCondition> mainCond = new ArrayList<>();
	// mainCond.add(EntityCondition.makeCondition("inventoryId",
	// EntityOperator.EQUALS, inventoryId));
//			   mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "7"));
	mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
		UtilMisc.toList("0", "1", "2", "3", "4", "5")));

	mainCond.add(EntityCondition.makeCondition("inventoryId", EntityOperator.EQUALS, inventoryId));
	mainCond.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "1"));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	List<GenericValue> crmBusinessItemList = delegator.findList("CrmBusinessItemByStatusId",
		EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);
	Debug.log("crmBusinessItemList =" + crmBusinessItemList);
	for (GenericValue crmBusinessItem : crmBusinessItemList) {
	    String businessId = crmBusinessItem.getString("businessId");
	    String followup = crmBusinessItem.getString("followup");

	    Debug.log("businessId =" + businessId);

	    Debug.log("crmBusinessItem =" + crmBusinessItem);
	    // 冷冻
	    BigDecimal estimatedFreeze = crmBusinessItem.getBigDecimal("estimatedFreeze");
	    if (UtilValidate.isNotEmpty(estimatedFreeze)) {
		estimatedFreezeTotal = estimatedFreezeTotal.add(estimatedFreeze);
	    }
	    // 冷藏
	    BigDecimal estimatedRefrigerate = crmBusinessItem.getBigDecimal("estimatedRefrigerate");
	    if (UtilValidate.isNotEmpty(estimatedRefrigerate)) {
		estimatedRefrigerateTotal = estimatedRefrigerateTotal.add(estimatedRefrigerate);
	    }
	    // 恒温
	    BigDecimal estimatedConstant = crmBusinessItem.getBigDecimal("estimatedConstant");
	    if (UtilValidate.isNotEmpty(estimatedConstant)) {
		estimatedConstantTotal = estimatedConstantTotal.add(estimatedConstant);
	    }
	    // 常温
	    BigDecimal estimatedNormal = crmBusinessItem.getBigDecimal("estimatedNormal");
	    if (UtilValidate.isNotEmpty(estimatedNormal)) {
		estimatedNormalTotal = estimatedNormalTotal.add(estimatedNormal);
	    }

	}

	result.put("estimatedFreeze", estimatedFreezeTotal);
	result.put("estimatedRefrigerate", estimatedRefrigerateTotal);
	result.put("estimatedConstant", estimatedConstantTotal);
	result.put("estimatedNormal", estimatedNormalTotal);
	Debug.log("result =" + result);
	return result;

    }

    private static Map forecastInventory(Delegator delegator, String inventoryId) {
	Map result = new HashMap();
	BigDecimal estimatedFreezeTotal = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateTotal = BigDecimal.ZERO;
	BigDecimal estimatedConstantTotal = BigDecimal.ZERO;
	BigDecimal estimatedNormalTotal = BigDecimal.ZERO;

	BigDecimal estimatedFreezeNextMonth = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateNextMonth = BigDecimal.ZERO;
	BigDecimal estimatedConstantNextMonth = BigDecimal.ZERO;
	BigDecimal estimatedNormalNextMonth = BigDecimal.ZERO;
	BigDecimal estimatedFreezeNext2Month = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateNext2Month = BigDecimal.ZERO;
	BigDecimal estimatedConstantNext2Month = BigDecimal.ZERO;
	BigDecimal estimatedNormalNext2Month = BigDecimal.ZERO;
	BigDecimal estimatedFreezeNext3Month = BigDecimal.ZERO;
	BigDecimal estimatedRefrigerateNext3Month = BigDecimal.ZERO;
	BigDecimal estimatedConstantNext3Month = BigDecimal.ZERO;
	BigDecimal estimatedNormalNext3Month = BigDecimal.ZERO;

	// 销售人员 的商机
	ArrayList<EntityCondition> mainCond = new ArrayList<>();
	// mainCond.add(EntityCondition.makeCondition("inventoryId",
	// EntityOperator.EQUALS, inventoryId));
	mainCond.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "5"));
	mainCond.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	try {

	    List<GenericValue> crmBusinessList = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond, EntityOperator.AND), null, null, null, true);

	    for (GenericValue business : crmBusinessList) {
		Debug.log("business  =" + business);
		String businessId = business.getString("id");
		List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem",
			UtilMisc.toMap("businessId", businessId, "typeId", "1", "inventoryId", inventoryId), null,
			true);

		for (GenericValue crmBusinessItem : crmBusinessItemList) {
		    Debug.log("crmBusinessItem  =" + crmBusinessItem);
		    // 冷冻
		    BigDecimal estimatedFreeze = crmBusinessItem.getBigDecimal("estimatedFreeze");
		    java.sql.Date estimateDate = crmBusinessItem.getDate("estimateDate");

		    if (UtilValidate.isNotEmpty(estimatedFreeze)) {
			estimatedFreezeTotal = estimatedFreezeTotal.add(estimatedFreeze);
			if (WvDatetimeUtils.isNextMonth(estimateDate)) {
			    estimatedFreezeNextMonth = estimatedFreezeNextMonth.add(estimatedFreeze);
			}
			if (WvDatetimeUtils.isNext2Month(estimateDate)) {
			    estimatedFreezeNext2Month = estimatedFreezeNext2Month.add(estimatedFreeze);
			}
			if (WvDatetimeUtils.isNext3Month(estimateDate)) {
			    estimatedFreezeNext3Month = estimatedFreezeNext3Month.add(estimatedFreeze);
			}

		    }

		    // 冷藏
		    BigDecimal estimatedRefrigerate = crmBusinessItem.getBigDecimal("estimatedRefrigerate");
		    if (UtilValidate.isNotEmpty(estimatedRefrigerate)) {
			estimatedRefrigerateTotal = estimatedRefrigerateTotal.add(estimatedRefrigerate);
			if (WvDatetimeUtils.isNextMonth(estimateDate)) {
			    estimatedRefrigerateNextMonth = estimatedRefrigerateNextMonth.add(estimatedRefrigerate);
			}
			if (WvDatetimeUtils.isNext2Month(estimateDate)) {
			    estimatedRefrigerateNext2Month = estimatedRefrigerateNext2Month.add(estimatedRefrigerate);
			}
			if (WvDatetimeUtils.isNext3Month(estimateDate)) {
			    estimatedRefrigerateNext3Month = estimatedRefrigerateNext3Month.add(estimatedRefrigerate);
			}

		    }
		    // 恒温
		    BigDecimal estimatedConstant = crmBusinessItem.getBigDecimal("estimatedConstant");
		    if (UtilValidate.isNotEmpty(estimatedConstant)) {
			estimatedConstantTotal = estimatedConstantTotal.add(estimatedConstant);
			if (WvDatetimeUtils.isNextMonth(estimateDate)) {
			    estimatedConstantNextMonth = estimatedConstantNextMonth.add(estimatedConstant);
			}
			if (WvDatetimeUtils.isNext2Month(estimateDate)) {
			    estimatedConstantNext2Month = estimatedConstantNext2Month.add(estimatedConstant);
			}
			if (WvDatetimeUtils.isNext3Month(estimateDate)) {
			    estimatedConstantNext3Month = estimatedConstantNext3Month.add(estimatedConstant);
			}

		    }
		    // 常温
		    BigDecimal estimatedNormal = crmBusinessItem.getBigDecimal("estimatedNormal");
		    if (UtilValidate.isNotEmpty(estimatedNormal)) {
			estimatedNormalTotal = estimatedNormalTotal.add(estimatedNormal);
			if (WvDatetimeUtils.isNextMonth(estimateDate)) {
			    estimatedNormalNextMonth = estimatedNormalNextMonth.add(estimatedNormal);
			}
			if (WvDatetimeUtils.isNext2Month(estimateDate)) {
			    estimatedNormalNext2Month = estimatedNormalNext2Month.add(estimatedNormal);
			}
			if (WvDatetimeUtils.isNext3Month(estimateDate)) {
			    estimatedNormalNext3Month = estimatedNormalNext3Month.add(estimatedNormal);
			}

		    }

		}
	    }

	} catch (GenericEntityException e) {

	    Debug.log("forecastInventory");
	    Debug.log(e.getMessage());
	}
	// 然后统计 累加

	result.put("estimatedFreeze", estimatedFreezeTotal);
	result.put("estimatedRefrigerate", estimatedRefrigerateTotal);
	result.put("estimatedConstant", estimatedConstantTotal);
	result.put("estimatedNormal", estimatedNormalTotal);

	result.put("estimatedFreezeNextMonth", estimatedFreezeNextMonth);
	result.put("estimatedRefrigerateNextMonth", estimatedRefrigerateNextMonth);
	result.put("estimatedConstantNextMonth", estimatedConstantNextMonth);
	result.put("estimatedNormalNextMonth", estimatedNormalNextMonth);

	result.put("estimatedFreezeNext2Month", estimatedFreezeNext2Month);
	result.put("estimatedRefrigerateNext2Month", estimatedRefrigerateNext2Month);
	result.put("estimatedConstantNext2Month", estimatedConstantNext2Month);
	result.put("estimatedNormalNext2Month", estimatedNormalNext2Month);

	result.put("estimatedFreezeNext3Month", estimatedFreezeNext3Month);
	result.put("estimatedRefrigerateNext3Month", estimatedRefrigerateNext3Month);
	result.put("estimatedConstantNext3Month", estimatedConstantNext3Month);
	result.put("estimatedNormalNext3Month", estimatedNormalNext3Month);

	Debug.log("forecastInventory result =" + result);
	return result;

    }

    public static Map<String, Object> getCrmChildParty(DispatchContext ctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	List<Map<String, String>> childMap = new ArrayList<>();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String partyId = userLogin.getString("partyId");
	String _userLoginId = userLogin.getString("userLoginId");
	try {
	    List<GenericValue> userLoginList = delegator.findByAnd("UserLogin",
		    UtilMisc.toMap("superiorId", _userLoginId), null, false);
	    if (UtilValidate.isNotEmpty(userLoginList)) {
		for (GenericValue item : userLoginList) {
		    Map<String, String> m = new HashMap<>();
		    String userLoginId = item.getString("userLoginId");
		    String childPartyId = item.getString("partyId");
		    GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", childPartyId), false);
		    String name = person.getString("name");
		    if (UtilValidate.isEmpty(name)) {
			name = userLoginId;
		    }
		    m.put("name", name);
		    m.put("userLoginId", userLoginId);
		    childMap.add(m);
		}
	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	result.put("childMap", childMap);
	return result;
    }

    /**
     * 获取所有bu
     * 
     * @param ctx
     * @param context
     * @return
     */
    public static Map<String, Object> getAllBU(DispatchContext ctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	List<Map<String, String>> childMap = new ArrayList<>();
	try {
	    List<GenericValue> buList = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryTypeId", "BU_DEPARTMENT"), null, false);
	    if (UtilValidate.isNotEmpty(buList)) {
		for (GenericValue item : buList) {
		    Map<String, String> bu = new HashMap<>();
		    String name = item.getString("description");
		    String ownerBuId = item.getString("dictionaryCode");
		    bu.put("name", name);
		    bu.put("userLoginId", ownerBuId);
		    childMap.add(bu);
		}
	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	result.put("childMap", childMap);
	return result;
    }
    
    /**
     * 获取bu名称
     * 
     * @param ctx
     * @param context
     * @return
     */
    public static Map<String, Object> getBuNameById(DispatchContext ctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	String buId = (String) context.get("buId");
	List<Map<String, String>> childMap = new ArrayList<>();
	try {
	    List<GenericValue> buList = delegator.findByAnd("DataDictionary",
		    UtilMisc.toMap("dictionaryCode", buId), null, false);
	    GenericValue buInfo =EntityUtil.getFirst(buList);
	    if (UtilValidate.isNotEmpty(buInfo)) {
		    String name = buInfo.getString("description");
		    result.put("name", name);
	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	
	return result;
    }


    /**
     * 列出全部下属以及自己
     */
    public static Map<String, Object> listPersonBySuperiorId(DispatchContext ctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	List<Map<String, String>> nfsList = new ArrayList<>();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String partyIdSuperior = userLogin.getString("partyId");
	try {

	    Map<String, String> mapSuperior = new HashMap<>();
	    String userLoginIdSuperior = userLogin.getString("userLoginId");
	    // String partyId = userLogin.getString("partyId");
	    GenericValue personSuperior = delegator.findOne("Person", UtilMisc.toMap("partyId", partyIdSuperior),
		    false);
	    String nameSuperior = personSuperior.getString("name");
	    if (UtilValidate.isEmpty(nameSuperior)) {
		nameSuperior = userLoginIdSuperior;
	    }
	    // mapSuperior.put("person_code", userLoginIdSuperior);
	    mapSuperior.put("key", partyIdSuperior);
	    mapSuperior.put("value", partyIdSuperior);
	    mapSuperior.put("title", nameSuperior);
	    mapSuperior.put("text", nameSuperior);
	    nfsList.add(mapSuperior);

	    List<GenericValue> userLoginList = delegator.findByAnd("UserLogin",
		    UtilMisc.toMap("superiorId", userLoginIdSuperior), null, false);
	    if (UtilValidate.isNotEmpty(userLoginList)) {
		for (GenericValue item : userLoginList) {
		    Map<String, String> map = new HashMap<>();
		    String userLoginId = item.getString("userLoginId");
		    String childPartyId = item.getString("partyId");
		    GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", childPartyId), false);
		    String name = person.getString("name");
		    if (UtilValidate.isEmpty(name)) {
			name = userLoginId;
		    }
		    // map.put("person_code", userLoginId);
		    map.put("key", childPartyId);
		    map.put("value", childPartyId);
		    map.put("title", name);
		    map.put("text", name);
		    nfsList.add(map);
		}
	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}

	result.put("nfsList", nfsList);
	return result;
    }

    /**
     * 列出全部下属以及自己
     */
    public static Map<String, Object> listUserLoginBySuperiorId(DispatchContext ctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	List<Map<String, String>> nfsList = new ArrayList<>();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String partyIdSuperior = userLogin.getString("partyId");
	try {

	    Map<String, String> mapSuperior = new HashMap<>();
	    String userLoginIdSuperior = userLogin.getString("userLoginId");
	    GenericValue personSuperior = delegator.findOne("Person", UtilMisc.toMap("partyId", partyIdSuperior),
		    false);
	    String nameSuperior = personSuperior.getString("name");
	    if (UtilValidate.isEmpty(nameSuperior)) {
		nameSuperior = userLoginIdSuperior;
	    }
	    mapSuperior.put("key", userLoginIdSuperior);
	    mapSuperior.put("value", userLoginIdSuperior);
	    mapSuperior.put("title", nameSuperior);
	    mapSuperior.put("text", nameSuperior);
	    nfsList.add(mapSuperior);

	    List<GenericValue> userLoginList = delegator.findByAnd("UserLogin",
		    UtilMisc.toMap("superiorId", userLoginIdSuperior), null, false);
	    if (UtilValidate.isNotEmpty(userLoginList)) {
		for (GenericValue item : userLoginList) {
		    Map<String, String> map = new HashMap<>();
		    String userLoginId = item.getString("userLoginId");
		    String childPartyId = item.getString("partyId");
		    GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", childPartyId), false);
		    String name = person.getString("name");
		    if (UtilValidate.isEmpty(name)) {
			name = userLoginId;
		    }
		    map.put("key", userLoginId);
		    map.put("value", userLoginId);
		    map.put("title", name);
		    map.put("text", name);
		    nfsList.add(map);
		}
	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}

	result.put("nfsList", nfsList);
	return result;
    }
    
    public static String getBusinessTypeNameByCustomerId(String customerId){
    	
    	Delegator delegator = DelegatorFactory.getDelegator("default");

    	 String typeId_dictText = "";
 	    Map<String, GenericValue> typeIdMap = new HashMap();
 	   try {
 	    List<GenericValue> crmBusinessItemTypeInfo = delegator.findByAnd("CrmBusinessItemByTypeId",
 		    UtilMisc.toMap("customerId", customerId), null, true);
 	    for (GenericValue crmBusinessItemType : crmBusinessItemTypeInfo) {
 		typeIdMap.put(crmBusinessItemType.getString("typeId"), crmBusinessItemType);
 	    }
 	   // typeIdMap.values();
 	    for (String key : typeIdMap.keySet()) {
 		if ("1".equals(key)) {
 		    typeId_dictText = "仓储";
 		}
 		if ("2".equals(key)) {
 		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
 			typeId_dictText += "/";
 		    }
 		    typeId_dictText += "运输";
 		}
 		if ("3".equals(key)) {
 		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
 			typeId_dictText += "/";
 		    }
 		    typeId_dictText += "货代";
 		}
 		if ("4".equals(key)) {
 		    if (UtilValidate.isNotEmpty(typeId_dictText)) {
 			typeId_dictText += "/";
 		    }
 		    typeId_dictText += "库购";
 		}
 	    }
 	  } catch (GenericEntityException e) {
 		    Debug.logError(e.getMessage(), module);
 		}
 	  return typeId_dictText;
 	    //map.put("typeId_dictText", typeId_dictText);
    }

    public static String getPersonNameByUserLoginId(String userLoginId) {
	String result = userLoginId;

	try {
	    Delegator delegator = DelegatorFactory.getDelegator("default");

	    GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId), true);
	    if (UtilValidate.isEmpty(userLogin)) {
		return result;
	    }
	    String partyId = userLogin.getString("partyId");

	    GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), true);
	    if (UtilValidate.isEmpty(person)) {
		return result;
	    }
	    result = person.getString("name");
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}

	return result;
    }

    public static String getCrmBusinessEstimatedSalesAmount(String businessId) {
	String result = "0";

	try {
	    Debug.log(businessId, module);
	    Delegator delegator = DelegatorFactory.getDelegator("default");

	    List<GenericValue> crmBusinessItemList = delegator.findByAnd("CrmBusinessItem",
		    UtilMisc.toMap("businessId", businessId), null, false);

	    BigDecimal estimatedSalesAmountTotal = BigDecimal.ZERO;
	    for (GenericValue item : crmBusinessItemList) {
		Debug.log("all item id=" + item.getString("id"), module);
		Debug.log("all item =" + item, module);
		if (UtilValidate.isNotEmpty(item.getBigDecimal("estimatedSalesAmount"))) {
		    BigDecimal estimatedSalesAmount = item.getBigDecimal("estimatedSalesAmount");
		    Debug.log("estimatedSalesAmount" + estimatedSalesAmount, module);
		    estimatedSalesAmountTotal = estimatedSalesAmountTotal.add(estimatedSalesAmount);
		    Debug.log("estimatedSalesAmountTotal" + estimatedSalesAmountTotal, module);
		}

	    }

	    DecimalFormat df = new DecimalFormat("#,###.##");
	    result = df.format(estimatedSalesAmountTotal);
	    if (result.equals("0")) {
		result = "0.00";
	    }
//	    result = String.valueOf(estimatedSalesAmountTotal.setScale(2).doubleValue());
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}

	return result;
    }

    public static void main(String[] args) {
	BigDecimal estimatedSalesAmountTotal = BigDecimal.valueOf(0.123);
	System.out.println(new DecimalFormat("#,###.##").format(estimatedSalesAmountTotal));
    }

    /**
     * 运营周报
     */
    public static Map<String, Object> getCrmWmsDataReport(DispatchContext dctx, Map<String, ? extends Object> context) {

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));

	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getCrmWmsDataReport == start");
	String ownerUserId = userLogin.getString("userLoginId");
	// 所属bu
	String onlyBu = (String) context.get("onlyBu");
	List<String> baseIdList = new ArrayList();
	try {
	    if ("Y".equals(onlyBu)) {

		List<GenericValue> coRelationshipList = delegator.findByAnd("CoRelationship",
			UtilMisc.toMap("partyIdTo", ownerUserId, "statusId", "PARTY_ENABLED", "partyRelationshipTypeId",
				"COMPANY_EMPLOYEE"),
			null, true);
		if (UtilValidate.isNotEmpty(coRelationshipList)) {
		    for (int i = 0; i < coRelationshipList.size(); i++) {
			GenericValue coRelationship = coRelationshipList.get(i);
			String partyIdFrom = coRelationship.getString("partyIdFrom");
			baseIdList.add(partyIdFrom);
		    }
		}

	    }

	    EntityCondition mainCond = null;
	    List<EntityCondition> andExprs = FastList.newInstance();
	    if (UtilValidate.isNotEmpty(baseIdList)) {
		andExprs.add(EntityCondition.makeCondition("ownerBuId", EntityOperator.IN, baseIdList));
	    }
	    andExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "Y"));
	    andExprs.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));

	    if (andExprs.size() > 0) {
		mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);
	    }

	    // 按仓库统计 销售情况
	    List dataListByWarehouse = new ArrayList();

	    // 库存率对比
	    List cautionDataListByWarehouse = new ArrayList();

	    List orderBy = UtilMisc.toList("ownerBuId");
	    List<GenericValue> entityList = delegator.findList("CrmWmsInventory", mainCond, null, orderBy, null, true);

	    for (GenericValue entity : entityList) {
		Map<String, Object> map = FastMap.newInstance();
		Map<String, Object> cautionSalesDataMap = FastMap.newInstance();

		String id = entity.getString("id");
		String warehouseName = entity.getString("warehouseName");
		// 建设冷冻容量
		BigDecimal buildingFreeze = entity.getBigDecimal("buildingFreeze");
		buildingFreeze = UtilValidate.isEmpty(buildingFreeze) ? BigDecimal.ZERO : buildingFreeze;
		// 已使用冷冻
		BigDecimal physicalFreeze = entity.getBigDecimal("physicalFreeze");
		physicalFreeze = UtilValidate.isEmpty(physicalFreeze) ? BigDecimal.ZERO : physicalFreeze;

		// 建设冷藏容量
		BigDecimal buildingRefrigerate = entity.getBigDecimal("buildingRefrigerate");
		buildingRefrigerate = UtilValidate.isEmpty(buildingRefrigerate) ? BigDecimal.ZERO : buildingRefrigerate;
		// 已使用冷藏
		BigDecimal physicalRefrigerate = entity.getBigDecimal("physicalRefrigerate");
		physicalRefrigerate = UtilValidate.isEmpty(physicalRefrigerate) ? BigDecimal.ZERO : physicalRefrigerate;

		// 建设恒温容量
		BigDecimal buildingConstant = entity.getBigDecimal("buildingConstant");
		buildingConstant = UtilValidate.isEmpty(buildingConstant) ? BigDecimal.ZERO : buildingConstant;
		// 已使用恒温
		BigDecimal physicalConstant = entity.getBigDecimal("physicalConstant");
		physicalConstant = UtilValidate.isEmpty(physicalConstant) ? BigDecimal.ZERO : physicalConstant;

		// 建设常温容量
		BigDecimal buildingNormal = entity.getBigDecimal("buildingNormal");
		buildingNormal = UtilValidate.isEmpty(buildingNormal) ? BigDecimal.ZERO : buildingNormal;
		// 已使用常温
		BigDecimal physicalNormal = entity.getBigDecimal("physicalNormal");
		physicalNormal = UtilValidate.isEmpty(physicalNormal) ? BigDecimal.ZERO : physicalNormal;

		Map weekInventory = getWeekInventory(delegator, id);
//				 physicalFreeze = (BigDecimal) weekInventory.get("physicalFreeze");
//				 physicalRefrigerate = (BigDecimal) weekInventory.get("physicalRefrigerate");
//				 physicalConstant = (BigDecimal) weekInventory.get("physicalConstant");
//				 physicalNormal = (BigDecimal) weekInventory.get("physicalNormal");
		Debug.log("weekInventory =" + weekInventory);

		// 剩余量
		BigDecimal availableFreeze = buildingFreeze.subtract(physicalFreeze);
		BigDecimal availableRefrigerate = buildingRefrigerate.subtract(physicalRefrigerate);
		BigDecimal availableConstant = buildingConstant.subtract(physicalConstant);
		BigDecimal availableNormal = buildingNormal.subtract(physicalNormal);

		// 已用库存小计
		BigDecimal buildingTotal = buildingFreeze.add(buildingRefrigerate).add(buildingConstant)
			.add(buildingNormal);

		// 已用库存小计
		BigDecimal physicalTotal = physicalFreeze.add(physicalRefrigerate).add(physicalConstant)
			.add(physicalNormal);

		// 可用库存小计
		BigDecimal availableTotal = availableFreeze.add(availableRefrigerate).add(availableConstant)
			.add(availableNormal);

		BigDecimal buildingFreezeDivide = buildingFreeze;
		BigDecimal buildingRefrigerateDivide = buildingRefrigerate;
		BigDecimal buildingConstantDivide = buildingConstant;
		BigDecimal buildingNormalDivide = buildingNormal;
		BigDecimal buildingTotalDivide = buildingTotal;
		if (buildingFreezeDivide.compareTo(BigDecimal.ONE) < 0) {
		    buildingFreezeDivide = BigDecimal.ONE;
		}
		if (buildingRefrigerateDivide.compareTo(BigDecimal.ONE) < 0) {
		    buildingRefrigerateDivide = BigDecimal.ONE;
		}
		if (buildingConstantDivide.compareTo(BigDecimal.ONE) < 0) {
		    buildingConstantDivide = BigDecimal.ONE;
		}
		if (buildingNormalDivide.compareTo(BigDecimal.ONE) < 0) {
		    buildingNormalDivide = BigDecimal.ONE;
		}
		if (buildingTotalDivide.compareTo(BigDecimal.ONE) < 0) {
		    buildingTotalDivide = BigDecimal.ONE;
		}

		// 已使用冷冻与建设冷冻容量占比
		BigDecimal physicalFreezeRate = physicalFreeze.divide(buildingFreezeDivide, 2, BigDecimal.ROUND_HALF_UP)
			.multiply(new BigDecimal(100));
		// 已使用冷藏与建设冷藏容量占比
		BigDecimal physicalRefrigerateRate = physicalRefrigerate
			.divide(buildingRefrigerateDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		// 已使用恒温与建设恒温容量占比
		BigDecimal physicalConstantRate = physicalConstant
			.divide(buildingConstantDivide, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		// 已使用常温与建设常温容量占比
		BigDecimal physicalNormalRate = physicalNormal.divide(buildingNormalDivide, 2, BigDecimal.ROUND_HALF_UP)
			.multiply(new BigDecimal(100));
		// 已使用总计与建设总计容量占比
		BigDecimal physicalTotalRate = physicalTotal.divide(buildingTotalDivide, 2, BigDecimal.ROUND_HALF_UP)
			.multiply(new BigDecimal(100));

		map.put("warehouseName", warehouseName);

		map.put("buildingFreeze", buildingFreeze);
		map.put("buildingRefrigerate", buildingRefrigerate);
		map.put("buildingConstant", buildingConstant);
		map.put("buildingNormal", buildingNormal);
		map.put("buildingTotal", buildingTotal);

		// 已使用
		map.put("physicalFreeze", physicalFreeze);
		map.put("physicalRefrigerate", physicalRefrigerate);
		map.put("physicalConstant", physicalConstant);
		map.put("physicalNormal", physicalNormal);
		map.put("physicalTotal", physicalTotal);

		map.put("availableFreeze", availableFreeze);
		map.put("physicalFreezeRate", physicalFreezeRate);

		map.put("availableRefrigerate", availableRefrigerate);
		map.put("physicalRefrigerateRate", physicalRefrigerateRate);

		map.put("availableConstant", availableConstant);
		map.put("physicalConstantRate", physicalConstantRate);

		map.put("availableNormal", availableNormal);
		map.put("physicalNormalRate", physicalNormalRate);

		map.put("availableTotal", availableTotal);//全温区倒序
		map.put("physicalTotalRate", physicalTotalRate);

		Debug.log("map =" + map);
		dataListByWarehouse.add(map);

		cautionSalesDataMap.put("warehouseName", warehouseName);

		// 已使用
		cautionSalesDataMap.put("physicalFreeze", physicalFreeze);
		cautionSalesDataMap.put("physicalRefrigerate", physicalRefrigerate);
		cautionSalesDataMap.put("physicalConstant", physicalConstant);
		cautionSalesDataMap.put("physicalNormal", physicalNormal);
		cautionSalesDataMap.put("physicalTotal", physicalTotal);

	    }

	    Map<String, Object> workMap = FastMap.newInstance();
	    
	    Collections.sort(dataListByWarehouse, new Comparator<Map>() {
			@Override
			public int compare(Map obj1, Map obj2) {
			    int i = ((BigDecimal) obj2.get("availableTotal")).compareTo((BigDecimal) obj1.get("availableTotal"));// 倒序
			    return i;// 这里返回的只是一个int类型的数据
			}
		    });

	    workMap.put("dataListByWarehouse", dataListByWarehouse);
	    workMap.put("cautionDataListByWarehouse", cautionDataListByWarehouse);

	    workMap.put("fromDate", fromDate);
	    workMap.put("thruDate", thruDate);

	    result.put("workMap", workMap);
	    Debug.log("getCrmWmsDataReport == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    private static Map getWeekInventory(Delegator delegator, String id) {
	Map result = new HashMap();

	// 已使用冷冻
	BigDecimal physicalFreeze = BigDecimal.ZERO;
	// 已使用冷藏
	BigDecimal physicalRefrigerate = BigDecimal.ZERO;
	// 已使用恒温
	BigDecimal physicalConstant = BigDecimal.ZERO;
	// 已使用常温
	BigDecimal physicalNormal = BigDecimal.ZERO;

	result.put("physicalFreeze", physicalFreeze);
	result.put("physicalRefrigerate", physicalRefrigerate);
	result.put("physicalConstant", physicalConstant);
	result.put("physicalNormal", physicalNormal);
	return result;
    }

    public static Map<String, Object> setBusinessLastRemindTime(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getNotUpdateBusiness == start");

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	try {
	    String id = (String) context.get("id");

	    GenericValue gv = delegator.findOne("CrmBusiness", false, UtilMisc.toMap("id", id));
	    gv.set("lastRemindTime", thruDate);
	    delegator.store(gv);

	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    /**
     * 七天内无更新的商机个数
     */

    public static Map<String, Object> getNotUpdateBusiness(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Debug.log("getNotUpdateBusiness == start");

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	// Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));

	try {
	    String mobile = (String) context.get("mobile");

	    String ownerUserId = userLogin.getString("userLoginId");
	    if (UtilValidate.isNotEmpty(mobile)) {
		ownerUserId = mobile;
	    }

	    List mainCondUser = new ArrayList();

	    List mainCond_sevenDay = new ArrayList();

	    Timestamp fromDate_sevenDay = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));
	    mainCond_sevenDay.add(EntityCondition.makeCondition("ownerUserId", EntityOperator.EQUALS, ownerUserId));
	    mainCond_sevenDay
		    .add(EntityCondition.makeCondition("updateTime", EntityOperator.LESS_THAN, fromDate_sevenDay));
	    mainCond_sevenDay.add(EntityCondition.makeCondition("statusId", EntityOperator.IN,
		    UtilMisc.toList("0", "1", "2", "3", "4")));
		mainCond_sevenDay.add(EntityCondition.makeCondition("removed", EntityOperator.EQUALS, "N"));
	    // , "5"
	    // lastRemindTime
	    // 沉默商机(个数)
//			Long sevenDayCrmBusinessNum = delegator.findCountByCondition("CrmBusiness", EntityCondition.makeCondition(mainCond_sevenDay, EntityOperator.AND), null, null);

	    int sevenDayCrmBusinessNum = 0;
	    List<GenericValue> list = delegator.findList("CrmBusiness",
		    EntityCondition.makeCondition(mainCond_sevenDay, EntityOperator.AND), null, null, null, false);
	    for (GenericValue gv : list) {
		Timestamp lastRemindTime = gv.getTimestamp("lastRemindTime");
		if (UtilValidate.isNotEmpty(lastRemindTime)) {
		    Debug.log("lastRemindTime = " + lastRemindTime);
		    Debug.log("fromDate_sevenDay = " + fromDate_sevenDay);
		    if (lastRemindTime.compareTo(fromDate_sevenDay) <= 0) {
			sevenDayCrmBusinessNum = sevenDayCrmBusinessNum + 1;
		    }

		} else {
		    sevenDayCrmBusinessNum = sevenDayCrmBusinessNum + 1;
		}

	    }
	    Debug.log("sevenDayCrmBusinessNum = " + sevenDayCrmBusinessNum);

	    result.put("sevenDayCrmBusinessNum", sevenDayCrmBusinessNum);
	    Debug.log("getNotUpdateBusiness == end");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    /**
     * 判断商机七天内无更新
     */

    public static String getOneNotUpdateBusiness(Timestamp updateTime, Timestamp lastRemindTime) {
	String result = "N";
//		try {
	// Delegator delegator = DelegatorFactory.getDelegator("default");

	Timestamp thruDate = WvDatetimeUtils.getToDayTimestamp();
	List mainCondUser = new ArrayList();

	List mainCond_sevenDay = new ArrayList();

	Timestamp fromDate_sevenDay = WvDatetimeUtils.getLastDay(thruDate, new Long(-7));

	// GenericValue gv =delegator.findOne("CrmBusiness", false, UtilMisc.toMap("id",
	// id));

	// Timestamp updateTime =gv.getTimestamp("updateTime");

	Debug.log("updateTime = " + updateTime);
	Debug.log("fromDate_sevenDay = " + fromDate_sevenDay);
	if (updateTime.compareTo(fromDate_sevenDay) <= 0) {
	    // Timestamp lastRemindTime =gv.getTimestamp("lastRemindTime");
	    if (UtilValidate.isNotEmpty(lastRemindTime)) {
		Debug.log("lastRemindTime = " + lastRemindTime);
		Debug.log("fromDate_sevenDay = " + fromDate_sevenDay);
		if (lastRemindTime.compareTo(fromDate_sevenDay) <= 0) {
		    result = "Y";
		}

	    } else {
		result = "Y";
	    }

	}
	// }
	Debug.log("result = " + result);

	// result.put("sevenDayCrmBusinessNum", sevenDayCrmBusinessNum);
//		} catch (GenericEntityException e) {
//			Debug.logError(e.getMessage(), module);
//		}

	return result;
    }

    private static boolean isNumeric(String str) {
	Pattern pattern = Pattern.compile("[0-9]*");
	return pattern.matcher(str).matches();
    }
    
    public static Map<String, Object> syncWarehouseData(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();


	try {
	    String channel_id = (String) context.get("mobile");
	    String seq = (String) context.get("mobile");
	    String warehouse_id = (String) context.get("mobile");
	    String timestamp = (String) context.get("mobile");
	    String key = (String) context.get("mobile");
	    
//	    result.put("state", 1);
//	    result.put("errormess", "");
	    result.put("seq", "");
	    result.put("warehouse_id", "");
	    result.put("warehouse_name", "");
	    result.put("freeze_total", 0);
	    result.put("freeze_occupied", 0);
	    result.put("cold_total", 0);
	    result.put("cold_occupied", 0);
	    result.put("constant_total", 0);
	    result.put("constant_occupid", 0);
	    result.put("normal_total", 0);
	    result.put("normal_occupid", 0);
	    result.put("key", "");
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
}
